from fastapi import APIRouter, Depends
from sqlalchemy.exc import IntegrityError
from sqlalchemy.testing.pickleable import User

from database import get_db
from models.booking_model import DocSchedule
from schemas.doctor_schemas import *
from services.auth_service import require_user

from models.user_models import *

from datetime import date
from sqlalchemy.orm import Session

from schemas.doc_schedule_schemas import ScheduleCreate, ScheduleUpdate, DoctorScheduleResponse, \
    DoctorScheduleListResponse

from fastapi import HTTPException
from typing import List, Dict

router = APIRouter()

###医生排班表的增删改查
@router.get("/doc_schedules", response_model=List[Dict])
def get_all_schedules(db: Session = Depends(get_db), user: User = Depends(require_user(UserType.ADMIN))):
    schedules = db.query(DocSchedule).all()
    return [schedule.to_dict() for schedule in schedules]

@router.get("/doc_schedule/{schedule_id}", response_model=Dict)
def get_schedule(schedule_id: int, db: Session = Depends(get_db), user: User = Depends(require_user(UserType.ADMIN))):
    schedule = db.query(DocSchedule).filter(DocSchedule.ID == schedule_id).first()
    if not schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
    return schedule.to_dict()

@router.post("/doc_schedules", response_model=Dict)
def create_schedule(schedule: ScheduleCreate, db: Session = Depends(get_db), user: User = Depends(require_user(UserType.ADMIN))):
    try:
        schedule.check()
        db_schedule = DocSchedule(**schedule.dict())
        db.add(db_schedule)
        db.commit()
        db.refresh(db_schedule)
        return db_schedule.to_dict()
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except IntegrityError:
        raise HTTPException(status_code=400, detail="Schedule already exists or invalid doctor ID")

@router.put("/doc_schedules/{schedule_id}", response_model=Dict)
def update_schedule(schedule_id: int, schedule_update: ScheduleUpdate, db: Session = Depends(get_db), user: User = Depends(require_user(UserType.ADMIN))):
    try:
        schedule_update.check()
        db_schedule = db.query(DocSchedule).filter(DocSchedule.ID == schedule_id).first()
        if not db_schedule:
            raise HTTPException(status_code=404, detail="Schedule not found")
        
        update_data = schedule_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_schedule, key, value)
        
        db.commit()
        db.refresh(db_schedule)
        return db_schedule.to_dict()
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/doc_schedules/{schedule_id}")
def delete_schedule(schedule_id: int, db: Session = Depends(get_db), user: User = Depends(require_user(UserType.ADMIN))):
    db_schedule = db.query(DocSchedule).filter(DocSchedule.ID == schedule_id).first()
    if not db_schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
    db.delete(db_schedule)
    db.commit()
    return {"message": "Schedule deleted successfully"}

########



@router.get("/booking_schedules", response_model=DoctorScheduleListResponse,  tags=["booking"])
def get_doctors_by_schedule(
    schedule_date: date,
    # time_period: str = Query(..., regex="^(AM|PM)$"),
    department: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """
    根据日期、时间段和科室查询医生排班信息+该排班记录的  id
    - schedule_date: 排班日期
    - time_period: 时间段 (AM 或 PM)
    - department: 科室名称 (可选)
    返回:
    - 有符合条件医生: List[DoctorScheduleResponse] (包含余号为0的医生)
    - 无符合条件医生: {"message": "未搜索到符合您要求的医生"}
    """
    try:
        # 查询排班表
        query = db.query(DocSchedule).filter(
            DocSchedule.schedule_date == schedule_date
        )
        
        if department:
            query = query.filter(DocSchedule.department == department)
        
        schedules = query.all()
        
        if not schedules:
            return {"is_empty": True, "message": "该时间段内没有符合您要求的医生"}
            # return {"message": "该时间段内没有符合您要求的医生"}
        
        # 获取医生ID列表
        doctor_ids = [s.doctor_id for s in schedules]
        
        # 查询医生详细信息
        doctors = db.query(Doctor).filter(Doctor.ID.in_(doctor_ids)).all()
        doctor_map = {d.ID: d for d in doctors}
        
        # 组合结果
        results = []
        
        for schedule in schedules:
            doctor = doctor_map.get(schedule.doctor_id)
            if not doctor:
                continue

            
            results.append(DoctorScheduleResponse(
                schedule_id=schedule.ID,  # 添加 schedule_id
                doctor_info=doctor.to_dict(),
                am_remaining=schedule.am_remaining,
                pm_remaining=schedule.pm_remaining
            ))
        
        if not results:
            return {"is_empty": True, "message": "未搜索到符合您要求的医生"}
            # return {"message": "未搜索到符合您要求的医生"}
            
        # return results
        return {"is_empty": False, "results":results}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

 